package divestoclimb.checklist;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import divestoclimb.checklist.data.Checklist;
import divestoclimb.checklist.data.Template;
import divestoclimb.checklist.storage.DbAdapter;
import divestoclimb.checklist.storage.XmlAdapter;
import divestoclimb.util.ValidFilenameFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.SpannedString;

/**
 * An activity that exports all templates and checklists to their default
 * file locations.
 * @author Ben Roberts (divestoclimb@gmail.com)
 */
public class Backup extends AbsBackupRestore {
	
	private DbAdapter mDbHelper;
	private XmlAdapter mXmlHelper;
	private Cursor mTemplates, mChecklists;
	private Template mCurrentItem;
	
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		
		mDbHelper = new DbAdapter(this);
		mXmlHelper = new XmlAdapter(mDbHelper);
	}

	@Override
	public void onResume() {
		mDbHelper.open();
		mTemplates = mDbHelper.fetchTemplates(DbAdapter.KEY_TEMPLATE_NAME, -1);
		startManagingCursor(mTemplates);
		mChecklists = mDbHelper.fetchChecklists(DbAdapter.KEY_CHECKLIST_NAME, -1);
		startManagingCursor(mChecklists);
		super.onResume();
	}
	
	@Override
	public void onPause() {
		super.onPause();
		mDbHelper.close();
	}
	
	@Override
	protected int getItemCount() {
		return mTemplates.getCount() + mChecklists.getCount();
	}
	
	@Override
	protected String getNextItem() {
		if(mTemplates != null && mTemplates.getCount() > 0 && ! mTemplates.isLast()) {
			mTemplates.moveToNext();
			mCurrentItem = mDbHelper.fetchTemplateFromCursor(mTemplates);
			return String.format("%s: %s", getString(R.string.template),
					mCurrentItem.getName());
		} else if(mChecklists != null && mChecklists.getCount() > 0 && ! mChecklists.isLast()) {
			mChecklists.moveToNext();
			mCurrentItem = mDbHelper.fetchChecklistFromCursor(mChecklists);
			return String.format("%s: %s (%s)", getString(R.string.checklist),
					mCurrentItem.getName(), XmlAdapter.ISO8601_STANDARD.format(((Checklist)mCurrentItem).getStartDate()));
		} else {
			return null;
		}
	}

	@Override
	protected boolean processItem() {
		try {
			String pathName, name;
			InputFilter filter1 = new ValidFilenameFilter(), filter2 = new InputFilter.LengthFilter(255);
			Checklist cl = null;
			Template t = null;
			if(mCurrentItem instanceof Checklist) {
				cl = (Checklist)mCurrentItem; 
				name = cl.getName() + " " + XmlAdapter.ISO8601_STANDARD.format(cl.getStartDate());
				CharSequence charFilteredName = filter1.filter(name, 0, name.length(), null, 0, 0);
				name = charFilteredName == null? name: charFilteredName + "." + D2cChecklist.CHECKLIST_EXTENSION;
				CharSequence lengthFilteredName = filter2.filter(name, 0, name.length(), new SpannedString(""), 0, 0);
				pathName = D2cChecklist.CHECKLIST_DEFAULT_LOCATION.getPath() +
					File.separator + (lengthFilteredName == null? name: lengthFilteredName);
			} else {
				t = mCurrentItem;
				name = t.getName();
				CharSequence charFilteredName = filter1.filter(name, 0, name.length(), null, 0, 0);
				name = charFilteredName == null? name: charFilteredName + "." + D2cChecklist.TEMPLATE_EXTENSION;
				CharSequence lengthFilteredName = filter2.filter(name, 0, name.length(), new SpannedString(""), 0, 0);
				pathName = D2cChecklist.TEMPLATE_DEFAULT_LOCATION.getPath() +
					File.separator + (lengthFilteredName == null? name: lengthFilteredName);
			}
			File path = new File(pathName);
			if(! path.getParentFile().isDirectory()) {
				path.getParentFile().mkdirs();
			}
			FileWriter buffer = new FileWriter(path);
			boolean success;
			if(cl != null) {
				success = mXmlHelper.writeChecklist(cl, buffer);
			} else {
				success = mXmlHelper.writeTemplate(t, buffer);
			}
			buffer.flush();
			buffer.close();
			if(! success) {
				// The write failed, so clean up.
				path.delete();
			}
			return success;
		} catch(IOException e) {
			return false;
		}
	}
}